# coding:utf-8
from lxml import etree
import os
import sys

currentUrl = os.path.dirname(__file__)
proDir = os.path.abspath(os.path.join(currentUrl, os.pardir))
sys.path.append(proDir)


class ParseXML:

    def __init__(self):
        pass

    @property
    def root_url(self):
        return self.get_root_url()

    @property
    def global_params(self):
        return self.get_global_params()

    def read_xml(self, file_path):
        # 打开xml文档
        tree = etree.parse(file_path)
        return tree

    def find_all_nodes(self, file_path, pattern):
        tree = self.read_xml(file_path)
        return tree.findall(pattern)

    def get_root_url(self):
        file_path = os.path.join(proDir, "config", "api-config.xml")
        pattern = './rootUrl'
        root_url = self.find_all_nodes(file_path, pattern)[0].text
        return root_url

    def get_global_params(self):
        tmp = {}

        root_url = self.get_root_url()
        tmp['root_url'] = root_url

        file_path = os.path.join(proDir, "config", "api-config.xml")
        pattern = './/params/'
        params = self.find_all_nodes(file_path, pattern)

        for param in params:
            tmp[param.get('name')] = param.get('value')
        return tmp


if __name__ == '__main__':
    a = ParseXML()
    print(a.global_params)
